import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Row, Col, Input, Button, Table, message, Space, Modal } from 'antd'
import { UpOutlined, DownOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import moment from 'moment'
import style from '../filingCaseManage/CaseManage.module.less'
import OperateModal from '@components/LetterManage/OperateModal'
import DetailModal from '@components/LetterManage/DetailModal'
import { requestFiles } from '@js/request'
import { awaitWrap } from '@js/tool'

const { Item } = Form
const { confirm } = Modal

const layout = {
  labelCol: { flex: '72px' }
}

// 获取表格字段配置
function getColumns () {
  const list = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '案号',
      dataIndex: 'caseno_desc',
      key: 'caseno_desc',
      width: 130
    },
    {
      title: '状态',
      dataIndex: 'case_status',
      key: 'case_status',
      width: 100
    },
    {
      title: '经办秘书',
      dataIndex: 'processer',
      key: 'processer',
      width: 100
    },
    {
      title: '办案秘书',
      dataIndex: 'processer',
      key: 'processer',
      width: 100
    },
    {
      title: '信访内容',
      dataIndex: 'remark',
      key: 'remark',
      width: 150
    },
    {
      title: '处理结果',
      dataIndex: 'handing_result',
      key: 'handing_result',
      width: 150
    },
    {
      title: '处理时间',
      dataIndex: 'update_datetime',
      key: 'update_datetime',
      width: 150,
      render: v => {
        if (v) {
          return moment(v * 1000).format('YYYY-MM-DD')
        }
      }
    },
    {
      title: '处理人员',
      dataIndex: 'updater',
      key: 'updater',
      width: 150
    },
    {
      title: '操作',
      dataIndex: 'index',
      key: 'operate',
      width: 120,
      render: (value, line) => {
        return (
          <span className={style['operate-cell']}>
            <span onClick={() => this.getDetailData(line.id, false)}>详情</span>
            <span onClick={() => this.getDetailData(line.id, true)}>修改</span>
            <span onClick={() => this.confirmDel(line.id)}>删除</span>
          </span>
        )
      }
    }
  ]
  return list
}

class MyCase extends Component {
  state = {
    searchToggleBtn: false,
    loading: false,
    list: [],
    orderField: '',
    order: '',
    pagination: {
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    },
    modifyVisible: false,
    detailVisible: false,
    modifyData: {},
    personList: [] // 处理人可选列表
  }

  formRef = React.createRef()

  // 改变案件状态
  changeStatus (status) {
    this.setState({
      status,
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  // 获取案件数据
  getTableData (form) {
    form = form || this.formRef.current.getFieldsValue()
    const { pagination, orderField, order } = this.state
    const { current, pageSize } = pagination
    const condition = []
    if (form.caseno) {
      condition.push({ k: 'caseno_desc', o: 'like', v: `%${form.caseno_desc}%` })
    }
    if (form.processer) {
      condition.push({ k: 'processer', o: 'like', v: `%${form.processer}%` })
    }
    const data = {
      current,
      page_size: pageSize,
      condition: JSON.stringify(condition)
    }
    if (orderField && order) {
      data.order = order === 'ascend' ? 'asc' : 'desc'
      data.order_field = orderField
    }
    this.setState({ loading: true })
    this.$get('/api/xapc/feedback', data).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        this.setState({
          list: res.data.list.map((li, i) => {
            li.key = pageSize * (current - 1) + i + 1
            return li
          }),
          pagination: {
            ...pagination,
            total: res.data.total
          }
        })
      } else {
        return message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 表格请求变化
  tableChange ({ current, pageSize }, filters, sorter) {
    this.setState({
      orderField: sorter.field,
      order: sorter.order,
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getTableData()
    })
  }

  // 重置表格
  resetHandle () {
    this.formRef.current.resetFields()
    this.setState({
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  initFormByMeta () {
    const c = this.formRef.current
    const { formData = {}, status } = this.props.meta || {}
    if (status) {
      this.setState({
        status
      })
    }
    c.resetFields()
    c.setFieldsValue(formData)
    c.submit()
  }

  // 新增或修改回调
  async onOperate (data) {
    const params = { remark: data.remark, caseid: data.caseid }
    let url = '/api/xapc/feedback'
    let requestFn = this.$post.bind(this)
    let fileid = ''
    const file = data.file ? data.file.fileList : []
    if (file.length) {
      const hide = message.loading('文件上传中', 120)
      const [e, d] = await awaitWrap(requestFiles(file))
      hide()
      if (e) {
        return message.warning(e.message)
      }
      fileid = d.map(li => li.id).join()
    }
    params.fileid = fileid
    if (data.id) {
      url = `${url}/${data.id}`
      requestFn = this.$put.bind(this)
      params.handing_result = data.handing_result
      params.updater = data.updater
      params.updaterid = data.updaterid
      params.update_datetime = Math.floor(data.update_datetime / 1000)
    }
    const hide = message.loading('提交中', 120)
    requestFn(url, params)
      .then(res => {
        hide()
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.setState({
          modifyVisible: false
        }, () => {
          this.getTableData()
        })
      })
      .catch(() => hide())
  }

  // 获取详情数据
  getDetailData (id, isModify) {
    const hide = message.loading('加载中', 120)
    this.$get(`/api/xapc/feedback/${id}`)
      .then(res => {
        hide()
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        const d = { modifyData: res.data }
        if (isModify) {
          d.modifyVisible = true
        } else {
          d.detailVisible = true
        }
        this.setState(d)
      }).catch(() => hide())
  }

  // 删除信访二次提示
  confirmDel (id) {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: '您确定要删除该信访吗？',
      onOk: () => {
        this.delRequest(id)
      }
    })
  }

  // 删除信访请求
  delRequest (id) {
    const hide = message.loading('删除中', 120)
    this.$delete(`/api/xapc/feedback/${id}`)
      .then(res => {
        hide()
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        message.success('删除成功')
        this.getTableData()
      })
      .catch(() => hide())
  }

  // 获取可选的处理人列表
  getUpdaterOptions () {
    this.$get('/api/xapc/employee/getCaseProcesser')
      .then(res => {
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.setState({
          personList: res.data
        })
      })
  }

  componentDidUpdate (prev) {
    if (prev.meta !== this.props.meta) {
      this.initFormByMeta()
    }
  }

  componentDidMount () {
    this.getUpdaterOptions()
    this.initFormByMeta()
  }

  // 渲染搜索表单的展开和收起
  renderToggleBtns () {
    if (this.state.searchToggleBtn) {
      return (
        <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
          <span>展开</span>
          <UpOutlined />
        </Button>
      )
    }
    return (
      <Button type='link' onClick={() => { this.setState({ searchToggleBtn: !this.state.searchToggleBtn }) }}>
        <span>收起</span>
        <DownOutlined />
      </Button>
    )
  }

  render () {
    const columns = getColumns.call(this)
    return (
      <div className={style.container}>
        <OperateModal visible={this.state.modifyVisible} data={this.state.modifyData} hide={() => this.setState({ modifyVisible: false })} onFinish={d => this.onOperate(d)} personList={this.state.personList} />
        <DetailModal visible={this.state.detailVisible} data={this.state.modifyData} hide={() => this.setState({ detailVisible: false })} />
        <div className={style['title-line']}>
          <span>{this.props.title}</span>
        </div>
        <div className={style['search-container']}>
          <div className={style['search-form']}>
            <Form name='my_case_manage' {...layout} ref={this.formRef} onFinish={v => this.getTableData(v)}>
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='案号' name='caseno_desc'>
                    <Input placeholder='请输入案号' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='经办秘书' name='processer'>
                    <Input placeholder='请输入秘书' />
                  </Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col span={16} />
                <Col span={8}>
                  <Item>
                    <div className={style['search-btns']}>
                      <Button type='primary' ghost htmlType='submit'>搜索</Button>
                      <Button htmlType='reset' onClick={() => this.resetHandle()}>重置
                      </Button>
                      {/* {this.renderToggleBtns()} */}
                    </div>
                  </Item>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
        <div className={style['table-btns-line']}>
          <div className={style['table-tabs-container']}>
            <Space>
              <Button type='primary' ghost onClick={() => this.setState({ modifyVisible: true, modifyData: {} })}>新增</Button>
            </Space>
          </div>
        </div>
        <div className={style['table-container']}>
          <Table loading={this.state.loading} columns={columns} dataSource={this.state.list} pagination={this.state.pagination} onChange={(...args) => this.tableChange(...args)} />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
  }
})

export default connect(mapState, mapDispatch)(MyCase)
